#include "rtc_stream_manager.h"
#include "push_stream.h"

#include <rtc_base/logging.h>

namespace xrtc {

PushStream *RtcStreamManager::findPushStream(const std::string &stream_name) {
    auto it = m_push_streams.find(stream_name);
    if (it != m_push_streams.end()) {
        return it->second;
    }
            
    return nullptr;
}


// 创建推流, 如果已存在一路流，则先关闭再创建
int RtcStreamManager::createPushStream(uint64_t uid, const std::string &stream_name, 
                                       bool audio, bool video, uint32_t log_id, 
                                       rtc::RTCCertificate* certificate, std::string &offer) {
    PushStream* stream = findPushStream(stream_name);
    if (stream) {
        m_push_streams.erase(stream_name);
        delete stream;
    }

    stream = new PushStream(m_el, m_allocator.get(), uid, stream_name, audio, video, log_id);
    stream->start(certificate);
    offer = stream->createOffer();

    // 添加流的映射
    m_push_streams[stream_name] = stream;

    return 0;
}

// 处理客户端发送的answer
int RtcStreamManager::set_answer(uint64_t uid, const std::string &stream_name, const std::string &answer, 
                                 const std::string &stream_type, uint32_t log_id) {
    // 推流
    if (stream_type == "push") {
        PushStream* psuh_stream = findPushStream(stream_name);
        if (!psuh_stream) {
            RTC_LOG(LS_WARNING) << "Push stream not found, uid: " << uid 
                                << ", stream_name: " << stream_name
                                << ", log_id: " << log_id;
            return -1;        
        }

        if (uid != psuh_stream->getuid()) {
            RTC_LOG(LS_WARNING) << "uid invalid, uid: " << uid
                                << ", stream_name: " << stream_name
                                << ", log_id: " << log_id;
            return -1;
        }

        psuh_stream->set_remote_sdp(answer);
    } else if (stream_type == "pull") {
        // 拉流

    }

    return 0;
}

}